<?php

namespace addons\Flow\merchant\controllers;

use addons\Flow\common\models\Metadata;
use addons\Flow\common\models\Status;
use Yii;
use common\traits\Curd;
use common\models\base\SearchModel;
use common\enums\StatusEnum;
use addons\Flow\common\models\Works;
use yii\db\Expression;
use yii\web\NotFoundHttpException;

class WorksController extends BaseController
{
    use Curd;

    public $modelClass = Works::class;

    public function actionIndex()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'relations' => ['member' => ['realname']], // 关联 member 表的 nickname 字段
            'partialMatchAttributes' => ['content', 'member.realname'], // 模糊查询，注意 member_nickname 为关联表的别名 表名_字段
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);
//        Yii::$app->debris->p(Yii::$app->user->id);
        $search = $params = Yii::$app->request->queryParams;
        $created_time = [];
        if (!empty($search['SearchModel']['created_at'])) {
            list($start, $end) = explode('/', $params['SearchModel']['created_at']);
            $start = strtotime($start);
            $end = strtotime($end);
            $created_time = ['between', Works::tableName().'.created_at', $start, $end];
            unset($params['SearchModel']['created_at']);
        }
        $dataProvider = $searchModel->search($params);
        !empty($created_time) ? $dataProvider->query
            ->andWhere($created_time) : $dataProvider->query
            ->andFilterWhere([Works::tableName().'.merchant_id' => $this->getMerchantId()]);
//        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andFilterWhere([Works::tableName().'.merchant_id' => $this->getMerchantId()]);

        if ($role = Yii::$app->services->rbacAuthRole->getRole()) {
            $dataProvider->query->andWhere(['audit_id'=>Yii::$app->user->id]);
        }

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }
    public function actionCompleted()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'relations' => ['member' => ['realname']], // 关联 member 表的 nickname 字段
            'partialMatchAttributes' => ['content', 'member.realname'], // 模糊查询，注意 member_nickname 为关联表的别名 表名_字段
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);
        $search = $params = Yii::$app->request->queryParams;
        $created_time = [];
        if (!empty($search['SearchModel']['created_at'])) {
            list($start, $end) = explode('/', $params['SearchModel']['created_at']);
            $start = strtotime($start);
            $end = strtotime($end);
            $created_time = ['between', Works::tableName().'.created_at', $start, $end];
            unset($params['SearchModel']['created_at']);
        }
        $dataProvider = $searchModel->search($params);
        !empty($created_time) ? $dataProvider->query
            ->andWhere($created_time) : $dataProvider->query
            ->andFilterWhere([Works::tableName().'.merchant_id' => $this->getMerchantId()]);
        $dataProvider->query->andFilterWhere([Works::tableName().'.merchant_id' => $this->getMerchantId()]);
        $where = new Expression("FIND_IN_SET(:supplier, audit_ids)", [":supplier" => Yii::$app->user->id]);
        $dataProvider->query->andWhere($where);
        return $this->render('completed', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }
    public function actionAjaxApprove()
    {
        $id = Yii::$app->request->get('id', null);
        $works = $this->findModel($id);
        $model = $works->model::findOne($works->work_id);
        $radioList = [];
        foreach ($model->getNextStatuses() as $key => $nextStatus) {
            $radioList[$key] = $nextStatus['status']->getLabel();
        }
        asort($radioList,SORT_STRING);

//        Yii::$app->debris->p(ArrayHelper::arrayToArrays($radioList));
        if ($model->load(Yii::$app->request->post())) {
            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->render('ajax-approve', [
            'model' => $model,
            'radioList' => $radioList,
            'members' => Yii::$app->merchantsService->member->getMap(),
        ]);
    }
    public function actionReset()//提交重审，重置流程为apply状态
    {
        $id = Yii::$app->request->get('id', null);
        $works = $this->findModel($id);
        $model = $works->model::findOne($works->work_id);
        $audit = Status::find()->andWhere(['workflow_id' => $works->workflow_id, 'id' =>'apply', 'merchant_id' =>Yii::$app->user->identity->merchant_id ])->one();
        //确定审核人
        $metadata = Metadata::find()->andWhere(['workflow_id' => $works->workflow_id, 'status_id' =>'apply', 'merchant_id' =>Yii::$app->user->identity->merchant_id ])->asArray()->all();
        //某状态设置了元数据启用单独审核
        $flag = 0;
        if($metadata){
            $member_ids='';
            foreach ($metadata as $meta){
                if($meta['key']=='audit_id') $audit_id = $meta['value'];
                if($meta['key']=='member_id') $member_ids = $meta['value'];
                if($meta['key']=='end_mark'&&$meta['value']=='true') $flag=1;
            }
            //在单独审核的用户名单里情况
            if($flag==1&&in_array($works->member_id,explode(',',$member_ids))) $audit->audit_id = 0;
            if($flag==0&&in_array($works->member_id,explode(',',$member_ids))) $audit->audit_id = $audit_id;
            //不在单独审核用户名单里的情况
            if($flag==1&&!in_array($works->member_id,explode(',',$member_ids))) {
                if($audit->type==0&&$audit->audit_id) $audit->audit_id = $audit->audit_id;
                else if($audit->type==1&&$audit->role_id)  $audit->audit_id = Yii::$app->merchantsService->member->getLeaderRoleId($works->member_id,$audit->role_id);
            }
            if($flag==0&&!in_array($works->member_id,explode(',',$member_ids))) {
                if($audit->type==0&&$audit->audit_id) $works->audit_id = $audit->audit_id;
                else if($audit->type==1&&$audit->role_id)  $audit->audit_id = Yii::$app->merchantsService->member->getLeaderRoleId($works->member_id,$audit->role_id);
            }
        }
        //某状态未设置元数据的情况
        if(!$metadata) {
            if($audit->type==0&&$audit->audit_id)  $audit->audit_id = $audit->audit_id;
            else if($audit->type==1&&$audit->role_id) $audit->audit_id = Yii::$app->merchantsService->member->getLeaderRoleId($works->member_id,$audit->role_id);
        }
        if ($works->load(Yii::$app->request->post())) {
            // 开启事务
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $arr = $model->log?$model->log:[];
                $log=["id"=>Yii::$app->user->id,"time"=>time(),"action"=>$works->workflow_id.'/apply',"suggest"=>$works->mark.' 流程重置为申请状态。'];
                array_push($arr,$log);
                $log = json_encode($arr);

                $model::updateAll(['log'=>$log,'state' => 'apply','status' =>$works->workflow_id.'/apply'], ['id' =>$works->work_id]);
                Works::updateAll(['audit_id' => $audit->audit_id,'audit_ids' =>Null,'state'=>'apply'], ['id' =>$id]);
                //推送短信或消息
                if($model->remind==0&&$audit->audit_id>0&&Yii::$app->merchantsService->member->getMember($audit->audit_id)->mobile) Yii::$app->services->sms->send(Yii::$app->merchantsService->member->getMember($audit->audit_id)->mobile, '申请', 'audit');
                if($model->remind==1&&$audit->audit_id>0) Yii::$app->services->backendNotify->createMessage($works->content, Yii::$app->user->id, $audit->audit_id);


                $transaction->commit();

            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->message($e->getMessage(), $this->redirect(['index']), 'error');
            }
            return $this->message('重置成功，该工作将重新进入审核流程！', $this->redirect(['index']));
        }
        return $this->renderAjax('reset', [
            'model' => $works,
        ]);
    }
    /**
     * 编辑/创建
     *
     * @return mixed
     */
    public function actionEdit()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }

        return $this->render($this->action->id, [
            'model' => $model,
        ]);
    }
    public function actionAjaxEdit()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {

            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->renderAjax('ajax-edit', [
            'model' => $model,
        ]);
    }


    /**
     * 删除
     *
     * @param $id
     * @return mixed
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionDelete($id)
    {
        if ($this->findModel($id)->delete()) {
            return $this->message("删除成功", $this->redirect(['index']));
        }

        return $this->message("删除失败", $this->redirect(['index']), 'error');
    }

    /**
     * 回收站
     *
     * @return mixed
     */
    public function actionRecycle()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'partialMatchAttributes' => ['title'], // 模糊查询
            'defaultOrder' => [
                'sort' => SORT_ASC,
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
        $dataProvider->query
            ->andWhere(['<', 'status', StatusEnum::DISABLED]);
        return $this->render('recycle', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,

        ]);
    }

    protected function findModel($id)
    {
        /* @var $model \yii\db\ActiveRecord */
        if (empty($id) || empty(($model = $this->modelClass::findOne(['id' => $id])))) {
            $model = new $this->modelClass;
            return $model->loadDefaultValues();
        }

        return $model;
    }
}
